#ifndef BINTRAC_H
#define BINTRAC_H

int bintrac_port=0;
int bin_weight[4] = {0,0,0,0};

FILE * bin_com;

int parse_packet(char * buffer)
{
 int weight_size = 0, x = 0, y = 0, bin = 0;
 char neg = '+';
 
 while(buffer[weight_size]!=','){weight_size++; if(weight_size>7){return -3;}} //malformed packet}
 
 while(buffer[x]!='\n' && x < 40 && bin < 4)
 {
  neg = buffer[x];  x++;
  y = weight_size;
  while(y >= 0)
  {
   if(int(buffer[x]) - 48 < 0 || int(buffer[x])- 48 > 9){return -3;}  //chacter in middle of number is not a number
   bin_weight[bin] += int(buffer[x]) - 48 * 10^y;
   y--;
  }
  if(neg == '-'){bin_weight[bin] = bin_weight[bin] * -1;}
  x++; bin++;
 }
 return 1;
}

int poll_weights()
{
 char buffer[40];  
    
 if(bin_com == NULL){return -1;}
 int error = fputs("PP\r", bin_com);
 if(error == EOF){return -2;}
 fflush(bin_com);
 fseek(bin_com, 0, SEEK_END);
 if(!ftell(bin_com))
 {
  rewind(bin_com);
  Sleep(1000);
  fseek(bin_com, 0, SEEK_END);
  if(!ftell(bin_com)){return -4;}
 }
 fgets(buffer, 35, bin_com);
 error = parse_packet(buffer);
 return error;
}

int wakeup_bintrac()
{
 int x = 0, error = -1;
 
 printf("Attempting wakeup of bintrac...\n");
 
 while(x<avail_ports)
 {
  bin_com = fopen(COMPORTS[com_ports[x]],"w+");
  error = poll_weights();
  if(error == -1){printf("Error opening %s\n", COMPORTS[com_ports[x]]); fclose(bin_com);}
  else if(error == -2){printf("%s ", COMPORTS[com_ports[x]]); perror("Error"); fclose(bin_com);}
  else if(error == -3){printf("Error parsing packet from %s\n", COMPORTS[com_ports[x]]);  fclose(bin_com);}
  else if(error == -4){printf("Request timeout.\n");  fclose(bin_com);}
  else if(error == 1){break;}
  x++;                    
 }
 
 if(error == 1)
 {
  printf("Bintrac found!  Hopper weights: %d, %d, %d, %d\n",bin_weight[0], bin_weight[1], bin_weight[2], bin_weight[3]);     
 }
 else
 {
  printf("Wakeup failed!  WARNING:  Hopper information unavailable!\n");
 } 
 
 return 0;  
}

#endif
